package com.edu.base.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
//	
//	public static final String SOAP_CONTENT_TYPE = "application/soap+xml";
//	public static final String XML_CONTENT_TYPE = "text/xml";
//	public static final String CHAR_SET = "UTF-8";
//	public static final int CONNECTION_TIMEOUT = 3 * 1000;
//	public static final int SOCKET_TIMEOUT = 20 * 1000;
//	
//	//专门为了打印本地 接收 和 发送 的成对请求日志 
//	//private static final Logger ioLogger = Logger.getLogger("io");
//	
//	public static String postSoap(String url,String body){
//		return post(url, body,ContentType.create(SOAP_CONTENT_TYPE, CHAR_SET));
//	}
//	
//	public static String postXml(String url,String body){
//		return post(url, body,ContentType.create(XML_CONTENT_TYPE, CHAR_SET));
//	}
//	public static String getXml(String url){
//		return get(url, XML_CONTENT_TYPE, CHAR_SET);
//	}
//	public static String getXml(String url, String charset){
//		return get(url, XML_CONTENT_TYPE, charset);
//	}
//	
//	public static String post(String url){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpPost post = getPost(url);
//		return execute(client, post, CHAR_SET);
//	}
//	
//	public static String get(String url){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpGet get = getGet(url);
//		return execute(client, get, CHAR_SET);
//	}
//	public static String get(String url,String CHAR_SET){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpGet get = getGet(url);
//		return execute(client, get, CHAR_SET);
//	}
//	
//	public static String post(String url,String body,int timeOut){
//		ContentType ct = ContentType.create(XML_CONTENT_TYPE, CHAR_SET);
//		
//		return post(url,body,ct,timeOut);
//	}
//	public static String post(String url,String body,String contentType){
//		ContentType ct = ContentType.create(XML_CONTENT_TYPE, CHAR_SET);
//		if(contentType != null){
//			ct = ContentType.parse(contentType);
//		}
//		return post(url,body,ct);
//	}
//	public static String post(String url, Map<String, String> params){
//		ContentType ct = ContentType.create(XML_CONTENT_TYPE, CHAR_SET);
//		return post(url,params,ct);
//	}
//	public static String post(String url, Map<String, String> params,String contentType){
//		ContentType ct = ContentType.create(XML_CONTENT_TYPE, CHAR_SET);
//		if(contentType != null){
//			ct = ContentType.parse(contentType);
//		}
//		return post(url,params,ct);
//	}
//	private static String get(String url,String contentType,String charset){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpGet get = getGet(url);
//		//ioLogger.info("request-get:" + url);
//		String result = execute(client, get, charset);
//		//ioLogger.info("response-get:" + result);
//		return result;
//	}
//	private static String post(String url,String body,ContentType contentType){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpPost post = getPost(url);
//		StringEntity se = new StringEntity(body,contentType);
//		post.setEntity(se);
//		//ioLogger.info("request-post:" + body);
//		String result = execute(client, post, contentType.getCharset().displayName());
//		//ioLogger.info("response-post:" + result);
//		return result;
//	}
//	private static String post(String url,String body,ContentType contentType,int timeout){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpPost post = getPost(url,timeout);
//		StringEntity se = new StringEntity(body,contentType);
//		post.setEntity(se);
//		//ioLogger.info("request-post:" + body);
//		String result = execute(client, post, contentType.getCharset().displayName());
//		//ioLogger.info("response-post:" + result);
//		return result;
//	}
//	public static String postFile(String url,Map<String,String> params,Map<String,File> files,int timeOut){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpPost post = getPost(url,timeOut);
//		MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
//        builder.setCharset(Consts.UTF_8);
//        
//	
//        JSONObject jsonParam=new JSONObject();
//        if (params != null)
//        for (Map.Entry<String, String> entry : params.entrySet()) {
//        	jsonParam.put(entry.getKey(), entry.getValue());
//           
//        } 
//        StringBody contentBody = new StringBody(jsonParam.toJSONString(),ContentType.APPLICATION_JSON);
//        builder.addPart("data", contentBody);
//        for (Map.Entry<String, File> entry : files.entrySet()) {
//        	String fileName=entry.getKey();
//            FileBody fb = new FileBody(entry.getValue(), ContentType.DEFAULT_BINARY);
//        	builder.addPart(fileName, fb);
//           
//        } 
//        builder.setContentType(ContentType.MULTIPART_FORM_DATA);
//        HttpEntity data = builder.build();
//        post.setEntity(data);
//		//ioLogger.info("request-post:" + body);
//		String result = execute(client, post, "utf-8");
//		//ioLogger.info("response-post:" + result);
//		return result;
//	}
//	private static String post(String url, Map<String, String> params,ContentType contentType){
//		CloseableHttpClient client = HttpClients.createDefault();
//		HttpPost post = getPost(url);
//		
//		 if (params != null) { 
//			 List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
//        
//             for (Map.Entry<String, String> entry : params.entrySet()) {
//         
//                 nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
//               
//             } 
//         	try {
//				post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));//这里修改了一下加了,"utf-8"，否则会中文乱码
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//     } 
//	
//		//ioLogger.info("request-post:" + body);
//		String result = execute(client, post, contentType.getCharset().displayName());
//		//ioLogger.info("response-post:" + result);
//		return result;
//	}
//	private static HttpGet getGet(String url){
//		HttpGet get = new HttpGet(url);
//		RequestConfig config = RequestConfig.custom()
//				.setConnectTimeout(CONNECTION_TIMEOUT)
//				.setSocketTimeout(SOCKET_TIMEOUT)
//				.build();
//		get.setConfig(config);
//		return get;
//	}
//	private static HttpPost getPost(String url){
//		HttpPost post = new HttpPost(url);
//		RequestConfig config = RequestConfig.custom()
//				.setConnectTimeout(CONNECTION_TIMEOUT)
//				.setSocketTimeout(SOCKET_TIMEOUT)
//				.build();
//		post.setConfig(config);
//		return post;
//	}
//	private static HttpPost getPost(String url,int timeout){
//		HttpPost post = new HttpPost(url);
//		RequestConfig config = RequestConfig.custom()
//				.setConnectTimeout(timeout)
//				.setSocketTimeout(timeout)
//				.build();
//		post.setConfig(config);
//		return post;
//	}
//    private static String execute(CloseableHttpClient client,HttpUriRequest request,String charset){
//		CloseableHttpResponse response = null;
//		try {
//			response = client.execute(request);
//			if(response.getStatusLine().getStatusCode() == 200){
//				return consume(response.getEntity(),charset);
//			}else{
//				return null;
//			}
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//			return null;
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}finally{
//			try {
//				if(response != null){
//					response.close();
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//				response = null;
//			}
//		}
//	}
//	private static String consume(HttpEntity entity,String charset){
//		StringBuilder sb = new StringBuilder();
//		BufferedReader reader = null;
//		try {
//			reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
//			String line = null;
//			while((line = reader.readLine())!= null){
//				sb.append(line + "\n");
//			}
//			return sb.toString();
//		} catch (UnsupportedOperationException e) {
//			e.printStackTrace();
//			return null;
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return null;
//		}finally{
//			if(reader != null){
//				try {
//					reader.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//					reader = null;
//				}
//			}
//		}
//	}
//	
	  public static void  downLoadFromUrl(String urlStr, File file) throws IOException {
	        URL url = new URL(urlStr);
	        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	        //设置超时间为3秒
	        conn.setConnectTimeout(3*1000);
	        //防止屏蔽程序抓取而返回403错误
	        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

	        //得到输入流
	        InputStream inputStream = conn.getInputStream();
	        //获取自己数组
	        byte[] getData = readInputStream(inputStream);

	        //文件保存位置
	        FileOutputStream fos = new FileOutputStream(file);
	        fos.write(getData);
	        if(fos!=null){
	            fos.close();
	        }
	        if(inputStream!=null){
	            inputStream.close();
	        }


	      //  System.out.println("info:"+url+" download success");
	    }
//
//	  public static DownLoadObj  downLoadFromUrl(String urlStr) throws IOException {
//	        URL url = new URL(urlStr);
//	        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//	        //设置超时间为3秒
//	        conn.setConnectTimeout(3*1000);
//	        //防止屏蔽程序抓取而返回403错误
//	        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//	        DownLoadObj dlo=new DownLoadObj();
//	        dlo.setSize(conn.getContentLengthLong());
//	      
//	        //得到输入流
//	        InputStream inputStream = conn.getInputStream();
//	        dlo.setInputStream(inputStream);
//	       return dlo;
//	    }
//          public static class DownLoadObj{
//        	  private Long size;
//        	  private InputStream inputStream;
//			public Long getSize() {
//				return size;
//			}
//			public void setSize(Long size) {
//				this.size = size;
//			}
//			public InputStream getInputStream() {
//				return inputStream;
//			}
//			public void setInputStream(InputStream inputStream) {
//				this.inputStream = inputStream;
//			}
//			
//        	  
//          }
	    /**
	     * 从输入流中获取字节数组
	     * @param inputStream
	     * @return
	     * @throws IOException
	     */
	    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
	        byte[] buffer = new byte[1024];
	        int len = 0;
	        ByteArrayOutputStream bos = new ByteArrayOutputStream();
	        while((len = inputStream.read(buffer)) != -1) {
	            bos.write(buffer, 0, len);
	        }
	        bos.close();
	        return bos.toByteArray();
	    }
//	public static void main(String[] args) {
//		
////		String url = "http://192.168.20.164:8082/api/ffmpegRemote/callFfmpegMethod";
////		Map<String,File> files =Maps.newHashMap();
////		files.put("wolege", new File("/Users/admin/Pictures/e0bc404655e242f79ff2bfc3e4123634.mp3"));
////		files.put("hahah", new File("/Users/admin/Pictures/c8baebd7e259ba370fd0e0ea3a587470.mp4"));
////		Map<String,String> params=Maps.newHashMap();
////		params.put("methodName", "accto");
////		String str = postFile(url, params, files);
////		System.out.println(str);
//	}
//	 /**
//    *
//    *
//    * @param url  支持https格式 get请求
//    * @return  返回json格式
//    */
//
//   public static JSONObject getHttps(String hsUrl) {
//       try {
//           URL url;
//
//           url = new URL(hsUrl);
//           HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
//           X509TrustManager xtm = new X509TrustManager() {
//               @Override
//               public X509Certificate[] getAcceptedIssuers() {
//                   // TODO Auto-generated method stub
//                   return null;
//               }
//
//               @Override
//               public void checkServerTrusted(X509Certificate[] arg0, String arg1)
//                       throws CertificateException {
//                   // TODO Auto-generated method stub
//
//               }
//
//               @Override
//               public void checkClientTrusted(X509Certificate[] arg0, String arg1)
//                       throws CertificateException {
//                   // TODO Auto-generated method stub
//
//               }
//           };
//
//           TrustManager[] tm = {xtm};
//
//           SSLContext ctx = SSLContext.getInstance("TLS");
//           ctx.init(null, tm, null);
//
//           con.setSSLSocketFactory(ctx.getSocketFactory());
//           con.setHostnameVerifier(new HostnameVerifier() {
//               @Override
//               public boolean verify(String arg0, SSLSession arg1) {
//                   return true;
//               }
//           });
//
//
//           InputStream inStream = con.getInputStream();
//           ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//           byte[] buffer = new byte[1024];
//           int len = 0;
//           while ((len = inStream.read(buffer)) != -1) {
//               outStream.write(buffer, 0, len);
//           }
//           byte[] b = outStream.toByteArray();//网页的二进制数据
//           outStream.close();
//           inStream.close();
//           String rtn = new String(b, "utf-8");
//           if (StringUtils.isNotBlank(rtn)) {
//               JSONObject object = JSONObject.parseObject(rtn);
//               return object;
//           }
//       } catch (Exception e) {
//           e.printStackTrace();
//       }
//       return null;
//   }

}
